/**
 * Author zdc
 * 程序主入口
 */
/*if(!window.opener){
	alert("请登录!");
	location.href="about:blank";
}*/
var userId=getUrlParameter("user-id");
Global.language=getUrlParameter("request-locale");
Global.type=getUrlParameter("type");
Global.code=getUrlParameter("code");
Global.encryptEid = userId;
Global.system = getUrlParameter("system");//判断系统是什么MGIS，MQ
Global.reportType = getUrlParameter("report");//判断Report是什么类型
Global.isMdp = getUrlParameter("isMdp");//判断Portal域

if(!userId){
	alert("请登录!");
	location.href="about:blank";
}
function logoClick() {
	location.reload();//重新刷新页面
};
require(["widgets/opManagers/GlobalOpManager",
         "widgets/thematicManager/ThematicManager",
         "widgets/icons/IconBase","esri/geometry/Point",
         "dojo/topic",
         "dojo/domReady!"],function(GlobalOpManager,ThematicManager,IconBase,Point,Topic){
	Global.globalOpManager=new GlobalOpManager({global:Global});
	Global.thematicManager=new ThematicManager();
	Global.thematicManager.getConfig();
	esri.config.defaults.io.alwaysUseProxy=false;
	esri.config.defaults.io.proxyUrl="proxy.jsp";
	setSystemView();
	getRights(Topic,Point);
});

function setSystemView(){
	if (Global.system && Global.system == "MQ"){
		dojo.addClass(dojo.body(),"mq");
	}
}


function getRights(Topic,Point){
	//获取权限
	$.ajax({
		type:'get',
		url:Global.useRight?"./services/userservice/":'./right.js',//
		data:{
			usereid:userId
		},
		dataType:'json',
		success:function(response){
			if(!response||response=="null"){
				alert("无权限!");
				location.href="about:blank";
				return;
			}
			Global.InitRight = true;//权限获取完成
			Topic.publish("MQInit");
			processRight(response);
			getClusterData(Topic);
			getInitParam(Topic,Point);
			getDic();
			getRegionRights();
			getMarketRights();
			getCityRights();
			if(dijit.byId("mapW"))dijit.byId("mapW").initLayers();
		},
		error:function(response){
			console.log("获取权限出错");
		}
	});
}

function getClusterData(Topic){
	$.ajax({
		type:'post',
		url:"./services/queryservice/getclusterdata/",
		data:{
			ppwhere:Global.ppDataRange + " and StoreStatus_EnName = 'Remain'",
			storewhere:Global.storeDataRange
		},
		dataType:'json',
		success:function(response){
			if(!response||response=="null"){
				return;
			}
			Global.clusterPP = response.pp;
			Global.clusterStore = response.store;
			if(!Global.cluster){
				Topic.publish("cluster");
			}
		},
		error:function(response){
			console.log("获取cluster出错");
		}
	});
}

function getInitParam(Topic,Point){
	showLoading();
	$.ajax({
		type:'post',
		url:'./services/queryservice/getuserextent?r='+Math.random(),
		data:{
//			eid:Global.loginUserEID
		},
		dataType:'json',
		success:function(response){
			callback=function(){

				//获取管理员配置
				Global.thematicManager.getConfig(
						function(){}
				);
				setLanguage();
				locationStore(Topic);
				/*setTimeout(function(){
					Topic.publish("configThematic","marketPP","0=0");
				},2000);*/
				if(!response)return;
				var data=response;
				var level=data.level;
				var center=new Point(data.center);
				if(level==null||center==null)return;
				dijit.byId("mapW").map.setLevel(level);
				dijit.byId("mapW").map.centerAt(center);
				hideLoading();
			};
			if(Global.mapLoaded){
				callback();
			}else{
				Topic.subscribe("map_loaded",callback);
			}
		},
		error:function(response){
			hideLoading();
		}
	});
}

//PMT跳转MGIS
function locationStore(Topic){
	if (Global.type && Global.code){
		setTimeout(function(){
			if (Global.type == "Pipeline"){
				Topic.publish("searchbycondition","PP",""+ioc.layers.pipeline.prefix+""+ioc.layers.pipeline.codeField+" = '"+Global.code+"'");
			}
			if (Global.type == "Store"){
				Topic.publish("searchbycondition","Store",""+ioc.layers.store.prefix+""+ioc.layers.store.codeField+" = '"+Global.code+"'");
			}
		},2000);
	}
}

function setLanguage(){
	var enAndcn = ioc.ENandCN;
	var classname = "";
	var type = "";
	var value = "";
	Global.enLayer.setVisibility(Global.language=="zh-en");
	Global.cnLayer.setVisibility(Global.language!="zh-en");
	for (var i = 0; i < enAndcn.length; i++){
		classname = enAndcn[i].classname;
		type = enAndcn[i].type;
		var doms = dojo.query("."+classname+"");//DOM结点
		if (doms){
			for (var j = 0; j < doms.length; j++){
				var dom = doms[j];
				if (Global.language == "zh-en"){//英文
    				value = enAndcn[i].en;  			
            	}else{//中文
            		value = enAndcn[i].cn;
            	}
    			if (type == "text"){
    				dom.innerHTML = value;
    			}else if (type == "title"){
    				dom.title = value;
    			}else{
    				
    			}
			}
		}
	}
}

function getDic(){
	$.ajax({
		type:'post',
		url:'./controlservice/DataMasterMappingAction/getDataMasterMappingInfo',
		data:{
		},
		dataType:'json',
		success:function(response){
			Global.selectSource=response;
		},
		error:function(response){
			console.log("获取全局字典表出错");
		}
	});
}


function getDicLabel(dic,code){
	dic=(Global.selectSource||{})[dic];
	if(dic){
		for(var item in dic){
			item=dic[item];
			if(item.Dict_Code==code){
				return item.Type_EnName;
			}
		}
	}
	return "";
}


function refreshLayer(layerid)
{
	if (dijit.byId("mapW").map.getLayer(layerid)){
		dijit.byId("mapW").map.getLayer(layerid).refresh();
	}
}


function log(type,name,description){
	var operation = "";
	var operationType ="";
	var operationDescription ="";
	operationType = type;
	if (description){
		operationDescription = name;
		operation= description;
	}else{
		var result = getLogOperation(name);
		operation = result.operator;
		operationDescription = result.operatordes;
	}
	var data={
			operation:operation,
			operationType:operationType,
			operationDescription:operationDescription
		};
	$.ajax({
		type:'post',
		url:'./controlservice/gis_Log/add',
		data:{
			model:JSON.stringify(data)
		},
		dataType:'json',
		success:function(response){
			console.log("log:"+name);
		},
		error:function(response){
			console.log("日志写入出错");
		}
    });
}

function getLogOperation(operation){
	//debugger;
	 var result = {};
	 for(var i= 0;i<ioc.ENandCN.length;i++){
	        var dom = ioc.ENandCN[i];
	        if(dom.en == operation || dom.cn == operation){
	        	result["operatordes"] = dom.operation;
	        	if (dom.operation2){
	        		result["operator"] = dom.operation2;
	        	}else{
	        		result["operator"] = dom.en;
	        	}
	        	break;
	        }
	 }
	 return result;
}

function unloadHandle(){
	var map=dijit.byId("mapW").map;
	var center=map.extent.getCenter().toJson();
	var level=map.getLevel();
	var data={level:level,center:center};
	$.ajax({
		type:'post',
		url:'./services/queryservice/adduserextent',
		data:{
			extent:JSON.stringify(data)
//			,
//			eid:Global.loginUserEID
		},
		dataType:'json',
		success:function(response){
			console.log("底图范围写入成功");
		},
		error:function(response){
			console.log("底图范围写入出错");
		}
	});
}
function processRight(obj){
	Global.rights=obj.Rights;//菜单权限
	
	Global.PPScopes = obj.PPScopes;//PP的数据范围
	Global.StoreScopes = obj.StoreScopes;//Store的数据范围
	Global.OtherScopes = obj.OtherScopes;//other的数据范围
	Global.PPMMs = obj.PPMMs;//PP的MM集合
	Global.StoreMMs = obj.StoreMMs;//Store的MM集合
	Global.OtherMMs = obj.OtherMMs;//其他的MM集合
	
	Global.loginUserEID = obj.UserInfo.Code;
	Global.loginUser=obj.UserInfo.NameENUS;//登陆的用户
	Global.mmRights=obj.OtherMMs;
	//数据权限
	var hasTrue=false;//
	var ppCodes=[];
	var ppstr;//带前缀、控制，pp权限
	var ppstr2;//不带前缀、控制，pp权限
	//store
	var storestr;//带前缀、控制，Store权限
	var storestr2;//不带前缀、控制，Store权限
	var storeCodes=[];
	var hasStoreTrue = false;
	
	for(var i in obj.Roles){
		var item=obj.Roles[i];
		if(item.UsePPScope){
			hasTrue=true;
		}else{//非控制
			ppCodes=ppCodes.concat(item.AssignedPPs);
		}
		
		if(item.UseStoreScope){
			hasStoreTrue=true;
		}else{//非控制
			storeCodes=storeCodes.concat(item.AssignedStores);
		}
	}
	//PP
	ppstr="("+ioc.layers.pipeline.prefix+ioc.layers.pipeline.codeField + " in ('"+ppCodes.join("','")+"') )";
	ppstr2 = "("+ioc.layers.pipeline.codeField + " in ('"+ppCodes.join("','")+"') )";
	//Store
	storestr="("+ioc.layers.store.prefix+ioc.layers.store.codeField + " in ('"+storeCodes.join("','")+"') )";
	storestr2 = "("+ioc.layers.store.codeField + " in ('"+storeCodes.join("','")+"') )";
	
	var dic={"102":"Region_Type_Code","103":"Market_Type_Code","104":"City_Type_Code","105":"Dist_Type_Code","106":"MM_Type_Code"};
	
	var scope={};//PP
	var storescope={};//Store
	var otherscope={};//Other
	for(var i in obj.PPScopes){
		var item=obj.PPScopes[i];
		var pro=item.Type+"";
		scope[pro]=scope[pro]||[];
		scope[pro].push(item.Code);
	}
	for(var i in obj.StoreScopes){
		var item=obj.StoreScopes[i];
		var pro=item.Type+"";
		storescope[pro]=storescope[pro]||[];
		storescope[pro].push(item.Code);
	}
	for(var i in obj.OtherScopes){
		var item=obj.OtherScopes[i];
		var pro=item.Type+"";
		otherscope[pro]=otherscope[pro]||[];
		otherscope[pro].push(item.Code);
	}
	
	
	//PP区域权限
	var cond=[];
	var condStr;
	for(var pro in scope){
		cond.push(" ###"+dic[pro]+" in ('"+scope[pro].join("','")+"') ");
	}
	condStr=cond.join(") or (");
	condStr="(("+condStr+"))";
	//Store区域权限
	var condstore=[];
	var condstoreStr;
	for(var pro in storescope){
		condstore.push(" ###"+dic[pro]+" in ('"+storescope[pro].join("','")+"') ");
	}
	condstoreStr=condstore.join(") or (");
	condstoreStr="(("+condstoreStr+"))";
	//Other区域权限
	var condother=[];
	var condotherStr;
	for(var pro in otherscope){
		condother.push(" ###"+dic[pro]+" in ('"+otherscope[pro].join("','")+"') ");
	}
	condotherStr=condother.join(") or (");
	condotherStr="(("+condotherStr+"))";
	
	
    //PP权限
	//带前缀、pp权限
	Global.ppDataRangeRegion="(" +ppstr+(hasTrue?(" or "+condStr):"")+")";
	//不带前缀、PP权限
	Global.ppDataRange="(" +ppstr2+(hasTrue?(" or "+condStr.split("###").join("")):"")+")" + " and (StoreStatus_EnName in ('Remain','Watch','Killed','Redundant','Rejected','Opened')) ";
	
	//Store权限
	Global.storeDataRangeRegion="(" +storestr+(hasStoreTrue?(" or "+condstoreStr):"")+")";
	//不带前缀、Store权限
	Global.storeDataRange="(" +storestr2+(hasStoreTrue?(" or "+condstoreStr.split("###").join("")):"")+")";
	
	//Other权限
	//带前缀、Other数据权限
	Global.dataRangeRegion=condotherStr;
	//不带前缀、Other数据权限
	Global.dataRange=condotherStr.split("###").join("");


	console.log(Global.dataRangeRegion);
	console.log(Global.ppDataRangeRegion);
}


//esri.config.defaults.io.errorHandler=function(){console.log(arguments)}